using System;
using System.Collections;
using System.Collections.Specialized;
using System.Xml;

using MediaWikiEngine.Domain;

namespace MediaWikiEngine.Command
{
	/// <summary>
	/// Summary description for Login.
	/// </summary>
	public class Login : BaseCommand
	{
		/// <summary>
		/// Constructor.
		/// </summary>
		/// <param name="parameters"></param>
		/// <param name="connection"></param>
		public Login(
			CommandParams parameters,
			WikiConnection connection)
			:
			base(parameters, connection)
		{
		}

        public Login(WikiConnection connection, string username, string password) : base(connection)
        {
            CommandParams parameters = new CommandParams();
            parameters["username"] = username;
            parameters["password"] = password;

            _params = parameters;
        }

		/// <summary>
		/// Creates a Wiki Login command using an Xml text writer.
		/// </summary>
		/// <param name="inXW"></param>
		static public void ToXml(
			XmlTextWriter inXW)
		{
			StartCommandToXml(inXW, "wiki:login");

			StartInputToXml(inXW);
			InputNameValueToXml(inXW, "username", "$$username");
			InputNameValueToXml(inXW, "password", "$$password");
			EndInputToXml(inXW);

			StartOutputToXml(inXW);
			OutputNameValueToXml(inXW, "loginsuccess", "$loginsuccess");
			EndOutputToXml(inXW);

			EndCommandToXml(inXW);
		}

		public override CommandResult Execute()
		{
			NameValueCollection formData = new NameValueCollection();

			formData.Add("wpName", _params["username"].ToString());
			formData.Add("wpPassword", _params["password"].ToString());
			formData.Add("wpLoginattempt", "Log in");
			formData.Add("wpRemember", 1.ToString());

			_conn.DoGet(_conn.Endpoint.LoginPage());
			_conn.DoPost(_conn.Endpoint.LoginSubmit(), formData);

			Hashtable results = new Hashtable();

            //extract the name
            string wikiname = "wiki";
            foreach (System.Net.Cookie cookie in _conn.Cookies)
            {
                if (cookie.Name.Contains("_session"))
                {
                    wikiname = cookie.Name.Remove(cookie.Name.LastIndexOf("_session"));
                    break;
                }
            }

            if (null != _conn.Cookies[string.Format("{0}UserName",wikiname)] && _conn.Cookies[string.Format("{0}UserName",wikiname)].Value.ToUpper() == _params["username"].ToString().ToUpper())
                results["loginsuccess"] = true;
            else
                results["loginsuccess"] = false;

			return new LoginResult(results);
		}
	}

    public class LoginResult : CommandResult
    {
        public LoginResult(Hashtable results)
            : base(results)
        {
        }

        public bool LoginSuccess
        {
            get
            {
                return GetData<bool>("loginsuccess");
            }
        }
    }
}
